import json
from random import randint

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from utils.captcha.captcha import captcha
from utils.yuntongxun.sms import CCP


class ImageCodeView(View):
    def get(self, request):
        data = request.GET
        imageCodeId = data.get('cur')
        preImageCodeId = data.get('pre')
        text, image = captcha.generate_captcha()
        try:
            redis_conn = get_redis_connection('verify_code')
            redis_conn.delete(preImageCodeId)
            redis_conn.setex(imageCodeId, 60 * 3, text)
        except Exception as e:
            print(e)

        return HttpResponse(image, content_type='imgae/jpg')


class SMSView(APIView):
    def post(self, request):
        # 1.接收数据
        data = request.data
        mobile = data.get('mobile')
        text = data.get('text')
        id = data.get('id')
        # 2.检验数据
        if not all([mobile, text, id]):
            return Response({'errno':9999,'errmsg':'参数不全'})
        redis_conn = get_redis_connection('verify_code')
        redis_flag = redis_conn.get('flag_%s'%mobile)
        if redis_flag:
            return Response({'errno':9999,'errmsg':'请稍候重试'})
        redis_text = redis_conn.get(id)
        if redis_text:
            redis_text = redis_text.decode()
        else:
            return Response({'errno':9999,'errmsg':'验证码过期'})
        if redis_text != text.upper():
            return Response({'errno':9999,'errmsg':'验证码错误'})
        # 3.处理业务
        sms_code = "%04s" % randint(0, 9999)
        print('短信验证码:' + sms_code)

        redis_conn.setex(mobile, 60 * 5, sms_code)
        redis_conn.setex('flat_%s' % mobile, 60, 1)
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, 5], 1)
        # from celery_task import handle
        # handle.send_sms_code.delay(mobile, sms_code, 5)

        # 4.返回响应
        res={
            "errno": "0",
            "errmsg": "发送成功"
        }
        return Response(res)
